from __future__ import annotations

import random
from typing import Dict, List, Literal, TypedDict

from faker import Faker


Section = Literal["测试段", "前工序", "装配段", "卷绕段"]
Status = Literal["NG项", "OK项", "缺失项"]


class Row(TypedDict):
    工段: Section
    全局工序名称: str
    可制造名称: str
    状态: Status
    其他信息: str


class TableData(TypedDict):
    name: str
    rows: List[Row]


faker = Faker("zh_CN")


PROCESS_SUFFIX_CANDIDATES = [
    "OCVB",
    "OCV2",
    "阳极模切",
    "阳极涂布",
    "阴极涂布",
    "叠片",
    "卷绕",
    "注液",
    "封装",
]

MANUFACTURABILITY_CANDIDATES = [
    "归一化测K导入",
    "极耳设计规范",
    "阳极涂布重量",
    "PG_OCV2静置时间合理性",
    "叠片层数一致性",
    "注液量窗口",
    "壳体封装扭矩",
]

SECTIONS: List[Section] = ["测试段", "前工序", "装配段", "卷绕段"]
STATUSES: List[Status] = ["NG项", "OK项", "缺失项"]


def _random_process_name() -> str:
    # 生成 LFP_M6UP_{suffix}
    suffix = random.choice(PROCESS_SUFFIX_CANDIDATES)
    return f"LFP_M6UP_{suffix}"


def _random_manufacturability_name() -> str:
    # 随机从候选或拼接短语
    if random.random() < 0.7:
        return random.choice(MANUFACTURABILITY_CANDIDATES)
    # 生成一个较自然的中文短语
    return f"{faker.word()}规范" if random.random() < 0.5 else f"{faker.word()}合理性"


def generate_table(name: str, num_rows: int = 30) -> TableData:
    rows: List[Row] = []
    for _ in range(num_rows):
        section = random.choice(SECTIONS)
        # 给状态一个轻微不均匀分布，更贴近真实：OK最多
        status = random.choices(
            STATUSES, weights=[3, 6, 2], k=1
        )[0]
        other = "详情" if random.random() < 0.4 else ""
        rows.append(
            Row(
                工段=section,
                全局工序名称=_random_process_name(),
                可制造名称=_random_manufacturability_name(),
                状态=status,
                其他信息=other,
            )
        )
    return TableData(name=name, rows=rows)


def generate_tables() -> Dict[str, TableData]:
    """生成两张表的数据，并返回字典，键为表代号 A/B。"""
    table_a = generate_table("ERP-25-2194_N_A", num_rows=72)
    table_b = generate_table("ERP-25-2194_N_B", num_rows=72)
    return {"A": table_a, "B": table_b}


